//用户管理类
import util from './utils';
const User = function() {
  const self = this;
  self.UserData = null;

  self.retryRegiser = 0;

  self.levelName = {
    0: "普通会员",
    10: "普通管家",
    20: "银牌管家",
    21: "金牌管家",
    22: "钻石管家",
    100: "运营专员",
  };
  self.quickLogin = function(success,login,up){
    wx.login({
      fail: function(res) {
        util.msg('我们无法获取您的个人信息!');
        login && login(res);
      },
      success: function(res) {
        let api     = util.api.CodeCheck2;
        let channel = util.getChannel('all');
        if (res.code) {
          util.log('code获取成功,进行认证!');
          util.request({
            url: api,
            data: {
              ekey: channel.hasOwnProperty('ekey') ? channel['ekey'] : '',
              from: channel.hasOwnProperty('from') ? channel['from'] : '',
              js_code: res.code
            },
            setToken: 2,
            loading: 2,
            handle: true,
            callback: function(result) {
              if (result.status === 'ok') {
                wx.setStorageSync('t_token',result.res.token);
                util.token = result.res.token;
                util.request({
                  url: util.api.userInfo,
                  handle: true,
                  setToken: 2,
                  loading: 2,
                  callback: function(result) {
                    if (result.status === 'ok') {
                      result.res.isGroup = false;
                      result.res.token = util.token;
                      success && success(result.res);
                    } else {
                      //弹出认证失败提示信息
                      self.clearUserInfo();
                      util.msg(result.msg);
                      login && login.call(this);
                    }
                  }
                });
              } else {
                util.msg(result.msg);
                login && login(result);
              }
            }
          });
        } else {
          util.msg(res.errMsg ? res.errMsg : '微信登录失败,请退出重试!');
          login && login(res);
        }
      }
    });
  };
  /**
   * 用户登录逻辑
   */
  self.login = function(success, login, up) {
    let update = up || false;
    //优先认证令牌
    wx.checkSession({
      success: function() {
        util.log('用户key有效,认证令牌!');
        self.tokenAuth(function(userInfo) {
          //令牌认证成功,直接回调登录成功
          self.setUserData(userInfo);
          success && success(userInfo);
        }, function() {
          /**
           * 令牌认证失败,开始登录处理
           */
          util.log('令牌认证失败,开始登录处理');
          self.UserLogin(success, login);
        }, false, update);
      },
      fail: function() {
        util.log('用户key过期,引导登录!');
        login && login();
      }
    });
  };
  /**
   * 本地令牌认证(会自动从本地数据获取令牌)
   */
  self.tokenAuth = function(success, login, tip, up) {
    let app     = getApp();
    let token   = wx.getStorageSync('token') || false;
    let key     = util.cache_get('encryptKey', false);
    let cUInfo  = util.cache_get('_uInfo', false);
    let loading = tip || false;
    let update  = up || false;
    //如果本地没有令牌,直接失败处理
    if (token === false) {
      util.log('未登录!');
      login && login.call(this);
      return false;
    }
    if (key === false) {
      util.log('没有key!');
      login && login.call(this);
      return false;
    } else {
      app.globalData.encryptKey = key;
    }
    if (cUInfo && update === false) {
      self.setUserData(cUInfo);
      success && success(cUInfo);
      return false;
    }
    if (loading === true) {
      // util.loading('自动登录中...');
    }
    util.request({
      url: util.api.userInfo,
      handle: true,
      loading: 2,
      callback: function(result) {
        util.closeLoading();
        if (result.status === 'ok') {
          util.log('认证令牌成功!');
          result.res.isGroup = false;
          util.cache_put('_uInfo', result.res);
          self.setUserData(result.res);
          success && success(result.res);
        } else {
          util.log('认证令牌失败!');
          //弹出认证失败提示信息
          util.msg(result.msg);
          self.clearUserInfo();
          login && login.call(this);
        }
      },
      error: function(result) {
        util.closeLoading();
        //请求失败时的处理
        util.msg('服务器异常,用户信息认证失败!');
        login && login.call(this);
      }
    });
  };
  /**
   * 获取微信授权设置项
   * @param key
   * @param success
   * @param auth
   * @param fail
   */
  self.getUserSetting = function(key, success, auth, fail) {
    wx.getSetting({
      success: function(res) {
        util.log('获取设置成功.', res);
        if (res.authSetting[key]) {
          success && success();
        } else {
          auth && auth();
        }
      },
      fail: function(res) {
        fail && fail();
      }
    });
  };
  /**
   * 用户登录认证+授权逻辑
   * @param success
   * @param login
   * @param SessionData
   */
  self.UserLogin = function(success, login, SessionData) {
    let self = this;
    let loginFunc = function(success, login, SessionData) {
      self.getUserCode(function(result) {
        // if (!result.hasOwnProperty('ifnew') || result.ifnew === true) {
          util.log('用户更新资料',result);
          wx.getUserInfo({
            withCredentials: true,
            lang: 'zh_CN',
            success: function(res) {
              /**
               * 获取资料成功再注册
               */
              self.UserReg(result, res, success, login);
            }
          });
        // } else {
        //   console.log('旧用户直接获取用户资料');
        //   self.getUserInfoByNet(success);
        // }
      }, function(res) {
        login && login(res);
      });
    };
    if (SessionData) {
      loginFunc(success, login, SessionData);
    } else {
      self.getUserSetting('scope.userInfo', function() {
        //直接走登录流程
        util.log('已授权,静默获取用户资料');
        loginFunc(success, login, SessionData);
      }, function() {
        //引导主动点击登录界面按钮
        util.log('未授权,需要弹窗');
        login && login();
      }, function() {
        wx.showModal({
          title: '您关闭了用户信息授权',
          content: '请点击右上角 -> 关于 -> 设置 -> 勾选用户信息,以便我们确认用户资料!',
          showCancel: false,
          success: function(confirm, cancel) {
            if (confirm === true) {
              wx.openSetting({
                success(res) {
                  util.log(res.authSetting);
                }
              })
            }
          }
        });
      });
    }
  };
  /**
   * 新用户注册调用
   * @param Session
   * @param res
   * @param success
   * @param fail
   * @constructor
   */
  self.UserReg = function(Session, res, success, fail) {
    if (res.errMsg === 'getUserInfo:ok') {
      //与服务器注册
      let channel = util.getChannel('all');
      let app     = getApp();
      let param   = {
        key: Session.key,
        encryptedData: res.encryptedData,
        signature: res.signature,
        iv: res.iv,
        ekey: channel.hasOwnProperty('ekey') ? channel['ekey'] : '',
        from: channel.hasOwnProperty('from') ? channel['from'] : '',
        rawData: res.rawData
      };
      console.log('regUser:Param', param);
      util.request({
        url: util.api.regUser,
        type: 'POST',
        loading: 2,
        handle: true,
        data: param,
        callback: function(res) {
          console.log('regUser:Res',res);
          if(res.status === 'ok'){
            self.retryRegiser = 0;
            /**
             * 主动拉一次用户资料
             */
            self.getUserInfoByNet(success, fail);
          }else{
            /**
             * 解密失败时的处理,自动重试一次
             */
            if(res.code === 2021 && self.retryRegiser === 0){
              console.log('retryRegiser',{retry:self.retryRegiser,code:res.code});
              self.retryRegiser         = 1;
              app.globalData.userInfo   = null;
              app.globalData.encryptKey = null;
              self.UserLogin(success,fail);
            }else{
              self.retryRegiser = 0;
              fail && fail(res);
            }
          }
        }
      });
    } else {
      fail && fail(res);
    }
  };
  /**
   * 从网络获取用户信息
   * @param success
   * @param fail
   */
  self.getUserInfoByNet = function(success, fail) {
    util.request({
      url: util.api.userInfo,
      handle: true,
      loading: 2,
      callback: function(result) {
        if (result.status === 'ok') {
          result.res.isGroup = false;
          util.cache_put('_uInfo', result.res);
          self.setUserData(result.res);
          success && success(result.res);
        } else {
          //弹出认证失败提示信息
          self.clearUserInfo();
          util.msg(result.msg);
          fail && fail.call(this);
        }
      }
    });
  };
  /**
   * 设置本地用户信息
   */
  self.setUserData = function(userInfo) {
    if (userInfo) {
      userInfo['common']['pea_blance_big'] = parseInt(userInfo['common']['pea_blance'])
      let dou = parseInt(userInfo['common']['pea_blance'])
      if (dou > 9999) {
        userInfo['common']['pea_blance_big'] = Math.floor(dou / 10000 * 100) / 100 + '万'
      }
      if (100000000 > dou && dou > 9999999) {
        userInfo['common']['pea_blance_big'] = Math.floor(dou / 10000000 * 100) / 100 + '千万'
      }
    }


    let appInstance = getApp();
    userInfo && (userInfo['shop_info'] = {});
    if (JSON.stringify(self.UserData) === JSON.stringify(userInfo)) {
      return false;
    }
    self.UserData = userInfo;
    appInstance.globalData.userInfo = userInfo;
    appInstance.triggerEvent('upUserInfo', userInfo);
  };
  /**
   * 获取用户资料
   * @param success
   * @param login
   * @param up
   */
  self.getUserInfo = function(success, login, up) {
    let update = up || false;
    let app = getApp();
    if (app.globalData.userInfo === null || update === true) {
      self.login(function(userInfo) {
        app.globalData.userInfo = userInfo;
        success && success(userInfo);
      }, function(res) {
        login && login(res);
      });
    } else {
      success && success(app.globalData.userInfo);
    }
  };
  /**
   * 获取用户解密KEY
   * @param success
   * @param fail
   * @param token
   * @param type
   */
  self.getUserCode = function(success, fail, token,type) {
    let setT = token || 0;
    let app = getApp();
    let key = util.cache_get('encryptKey');
    let localToken = util.cache_get('token');
    type = type || 1;
    let loginFuc = function(success, fail, setT) {
      wx.login({
        fail: function(res) {
          util.msg('我们无法获取您的个人信息!');
          fail && fail(res);
        },
        success: function(res) {
          let api = util.api.CodeCheck;
          if(type === 2){
            api = util.api.CodeCheck2;
          }
          if (res.code) {
            util.log('code获取成功,进行认证!');
            util.request({
              url: api,
              data: {
                js_code: res.code
              },
              setToken: setT,
              loading: 2,
              handle: true,
              callback: function(result) {
                let app = getApp();
                if (result.status === 'ok') {
                  app.globalData.encryptKey = result.res.key;
                  util.cache_put('encryptKey', result.res.key);
                  success && success(result.res);
                } else {
                  util.msg(result.msg);
                  fail && fail(result);
                }
              }
            });
          } else {
            util.msg(res.errMsg ? res.errMsg : '微信登录失败,请退出重试!');
            fail && fail(res);
          }
        }
      });
    };
    util.log('检测Session');
    wx.checkSession({
      success: function() {
        util.log('Session有效,检测本地KEY');
        if (app.globalData.encryptKey) {
          key = app.globalData.encryptKey;
        }
        /**
         * 同时检测本地Token存在与否
         */
        if (key) {
          success && success({
            key: key
          });
        } else {
          util.log('本地没有KEY,走login');
          loginFuc(success, fail, setT);
        }
      },
      fail: function() {
        util.log('用户key过期,走login登录!');
        loginFuc(success, fail, setT);
      }
    });
  };
  /**
   * 获取用户级别格式化信息
   * @param userInfo
   * @param info
   * @returns {string|{grade}}
   */
  self.getUserLevelTag = function(userInfo, info) {
    let levelName = '普通会员';
    let res = info || false;
    let userLevelName = this.levelName;
    if (!userInfo.hasOwnProperty('grade')) {
      userInfo.grade = 0;
    }
    userInfo.isGroup = false;
    if (userLevelName.hasOwnProperty(userInfo.grade)) {
      levelName = userLevelName[userInfo.grade];
    }
    if (userInfo.isGroup && levelName === '普通会员') {
      levelName = '普通管家';
    }
    userInfo['levelName'] = levelName;
    if (res === false) {
      return levelName;
    }
    return userInfo;
  };
  self.clearUserInfo = function() {
    let app = getApp();
    util.cache_remove('_uInfo');
    util.cache_remove('token');
    util.cache_remove('encryptKey');
    app.globalData.encryptKey = null;
  };
  self.getNoticeReadNumber = function(up, callback) {
    let update = up || false;
    let getSysMsg = function(up, callback) {
      let update = up || false;
      let c_key = 'read_sys_list';
      let c_info = util.cache_get(c_key);
      if (!c_info || update !== false) {
        util.request({
          url: util.api.GetSystemMsg,
          data: {
            page: 1,
            limit: 30
          },
          callback: function(result) {
            util.cache_put(c_key, result.res, 120);
            callback && callback(result.res);
          }
        });
      } else {
        callback && callback(c_info);
      }
    };
    getSysMsg(update, function(msg) {
      let _noRead = 0;
      let _readData = util.cache_get('read_msg', {});
      for (let i = 0; i < msg['list'].length; i++) {
        let id = msg['list'][i]['Id'];
        if (!_readData.hasOwnProperty(id)) {
          _noRead++;
        }
      }
      callback && callback(_noRead);
    });
  };
  self.setNoticeReadNumber = function(id, callback) {
    let _readData = util.cache_get('read_msg', {});
    if (!_readData.hasOwnProperty(id)) {
      _readData[id] = 1;
    }
    util.cache_put('read_msg', _readData);
  };
  /**
   * 获取购物车商品数量
   */
  self.getMyCartSum = function(callback) {
    return false;
    if (self.UserData.hasOwnProperty('uid') && self.UserData['uid'] > 0) {
      util.request({
        url: 's/yddgoods/GetMyCartSum',
        handle: true,
        error: function() {},
        callback: function(result) {
          if (result.status !== 'ok') {
            result.res = {
              my_cart_amount: 0,
              my_cart_goods_amount: 0,
            };
          }
          if (result.res.hasOwnProperty('my_cart_goods_amount') && result.res.my_cart_goods_amount > 0) {
            wx.setTabBarBadge({
              index: 2,
              text: '' + result.res.my_cart_goods_amount
            })
          } else {
            wx.removeTabBarBadge({
              index: 2,
            });
          }
          callback && callback(result.res);
        }
      })
    } else {
      wx.removeTabBarBadge({
        index: 2,
      });
      callback && callback({
        my_cart_goods_amount: 0,
        my_cart_amount: 0
      })
    }
  };
  /**
   * 获取当前跟踪参数
   * @returns {{ekey: string, shareUid: number}}
   */
  self.getShareParam = function(s_uid) {
    let ekey = '';
    let fstr = '';
    let channel = util.getChannel('all');
    let result = {};
    s_uid = util.fixInt(s_uid);
    if (channel.hasOwnProperty('ekey')) {
      ekey = channel['ekey'];
    }
    if (channel.hasOwnProperty('fstr')) {
      fstr = channel['fstr'];
    }
    if (s_uid <= 0 && channel.hasOwnProperty('uid')) {
      s_uid = util.fixInt(channel['uid']);
    }
    if (self.UserData) {
      if (s_uid <= 0) {
        s_uid = util.fixInt(self.UserData.uid);
      }
      // if (s_uid <= 0 && self.UserData.hasOwnProperty('parrent') && self.UserData.parrent.uid) {
      //   s_uid = util.fixInt(self.UserData.parrent.uid);
      // }
      if (!ekey && self.UserData.hasOwnProperty('ekey')) {
        ekey = self.UserData['ekey'];
      }
      if (!fstr && self.UserData.hasOwnProperty('fstr')) {
        fstr = self.UserData['fstr'];
      }
    }
    result['fstr'] = fstr;
    result['ekey'] = ekey;
    result['shareUid'] = s_uid;
    return result;
  };
  /**
   * 获取用户首页相关配置
   * @param options
   * @returns {{popup: number, group_id: number, channel: {ekey: string, shareUid: number}, home: string}}
   */
  self.getUserHome = function(options) {
    let userInfo = self.UserData;
    let channel = self.getShareParam(options.hasOwnProperty('uid') ? options['uid'] : 0);
    let result = {
      channel: channel, //跟踪相关信息
      group_id: 0, //要展示的店主UID
      home: 'basic', //要展示的页面，group:团长店铺，basic:默认首页
      popup: 0, //要展示的弹窗,0:不弹,1:提示绑定管家,2:提示下载APP
    };
    util.log(channel, userInfo);
    result['group_id'] = channel.shareUid;
    if (result['group_id'] > 0) {
      result['home'] = 'group';
    }
    /**
     * 未登录用户显示默认首页
     */
    if (!userInfo || !userInfo.hasOwnProperty('uid') || userInfo.uid <= 0) {
      return result;
    }
    /**
     * 有跟踪信息并且不是当前用户相关的。
     */
    if (channel.shareUid > 0 && userInfo.uid !== channel.shareUid) {
      return result;
    }
    /**
     * 先判断自身信息
     * 如果是团长，并完成了任务
     */
    if (userInfo.grade >= 10) {
      if (userInfo['album_canshare'] === false) {
        result['group_id'] = userInfo.uid;
        result['home'] = 'group';
      } else {
        result['group_id'] = userInfo.uid;
        result['home'] = 'basic';
        result['popup'] = 2;
      }
      return result;
    }
    /**
     * 自身不是管家，再判断上级信息
     */
    if (typeof(userInfo.parrent.uid) !== 'undefined' && userInfo.parrent.uid > 0) {
      //上级完成了任务，显示上级小店,不弹窗
      if (userInfo['parrent']['album_canshare'] === false) {
        result['group_id'] = userInfo.parrent.uid;
        result['home'] = 'group';
        result['popup'] = 0;
      } else {
        result['group_id'] = 0;
        result['home'] = 'basic';
        result['popup'] = 0;
      }
      return result;
    }
    /**
     * 没有上级，判断渠道，有渠道不提示，
     */
    if (typeof(userInfo['channel_uid']) !== 'undefined' && userInfo['channel_uid'] > 0) {
      result['group_id'] = 0;
      result['home'] = 'basic';
      result['popup'] = 2;
      return result;
    }
    result['group_id'] = 0;
    result['home'] = 'basic';
    result['popup'] = 1;
    return result;
  };
  /**
   * 用户UV上报接口
   * @param ekey
   * @constructor
   */
  self.UvTrackPut = function (ekey) {
    if(typeof ekey === 'undefined' || ekey.length <= 0){
      return;
    }
    wx.login({
      success: function(res) {
        if (res.code) {
          console.log('js_code获取成功!');
          util.request({
            url: '/userinfo/UvCheck',
            data: {
              js_code: res.code,
              ekey:ekey,
            },
            setToken: 2,
            loading: 2,
            handle: true,
            callback: function(result) {
              console.log('UvTrackPut',ekey,result);
            }
          });
        }
      }
    });
  }
};
const __User = new User();
__User.UserData = util.cache_get('_uInfo', {});
module.exports = __User;
